<template>
  <span class="component-countdown">
    <slot :remain="remain" :on="on"></slot>
  </span>
</template>
<script>
export default {
  name: 'r-countdown',
  model: {
    event: 'toggle',
    prop: 'on'
  },
  props: {
    period: {
      type: Number,
      default: () => 60
    },
    tick: {
      type: Number,
      default: () => 1
    },
    on: {
      type: Boolean,
      default: () => false
    }
  },
  data () {
    return {
      remain: this.period,
      tid: null
    }
  },
  watch: {
    on (to, from) {
      if (from === false && to === true) {
        this.clear()
        this.start()
      }
    }
  },
  methods: {
    step () {
      this.remain -= this.tick
      if (this.remain < 0) {
        this.remain = 0
      }
      if (this.remain === 0) {
        this.clear()
        this.$emit('toggle', false)
      }
    },
    clear () {
      let {tid} = this
      if (tid != null) {
        window.clearInterval(tid)
        this.tid = null
      }
    },
    start () {
      this.remain = this.period
      let {tick} = this
      this.tid = window.setInterval(this.step, tick * 1000)
    }
  }
}
</script>
<style>
  .component-countdown {
    word-break: keep-all;
    flex: 1;
  }
</style>
